﻿Imports System.Text
Imports System.Xml.Serialization
Imports System.IO
Imports System.Security.Cryptography

Public Class Common
    Private _applicationTitle As String
    Public Shared ReadOnly Property ApplicationTitle() As String
        Get
            Return "Tools 4 MFG"
        End Get
    End Property
    Public Shared ReadOnly Property Version() As String
        Get
            Return "Beta - 0.0.0.1"
        End Get
    End Property
    Shared _sbSystemMessage As New StringBuilder
    Public Shared Event updateMessage(ByVal sender As Object, ByVal e As MessageEventArgs)
    Private Shared _systemMessage As String
    Public Shared Property SystemMessage() As String
        Get
            Return _sbSystemMessage.ToString
        End Get
        Set(ByVal value As String)
            If Not String.IsNullOrEmpty(value) Then
                RaiseEvent updateMessage(Nothing, New MessageEventArgs(value))
            End If
        End Set
    End Property
    Public Shared Function GetUncSourcePathByDriveLetter(ByVal driveLetter As Char) As String
        If String.IsNullOrEmpty(driveLetter) Then Throw New ArgumentNullException("driveLetter")
        If (driveLetter < "a"c OrElse driveLetter > "z") AndAlso (driveLetter < "A"c OrElse driveLetter > "Z") Then Throw New ArgumentOutOfRangeException("driveLetter", "driveLetter must be a letter from A to Z")
        Dim P As New Process()
        With P.StartInfo
            .FileName = "net"
            .Arguments = String.Format("use {0}:", driveLetter)
            .UseShellExecute = False
            .RedirectStandardOutput = True
            .CreateNoWindow = True
        End With
        P.Start()
        Dim T As String = P.StandardOutput.ReadToEnd()
        P.WaitForExit()
        For Each Line As String In Split(CStr(T), vbNewLine)
            If Line.StartsWith("Remote name") Then Return Line.Replace("Remote name", "").Trim() & "\"
        Next
        Return Nothing
    End Function

    Public Shared Function GetUncSourcePathFronFilename(ByVal filename As String) As String
        Dim returnValue As String = filename

        If filename.IndexOf(":") > -1 Then
            Dim netpath As String = Common.GetUncSourcePathByDriveLetter(CChar(filename.Substring(0, 1)))
            If Not String.IsNullOrEmpty(netpath) Then
                returnValue = netpath & filename.Substring(2)
            End If
        End If
        Return returnValue
    End Function
    Public Shared Function ensureSlash(ByRef value As String) As String
        If String.IsNullOrEmpty(value) Then Return ""
        value = Strings.Trim(value)
        If value.Length = 0 Then Return ""
        If value.Substring(value.Length - 1) <> "\" Then value = value & "\"
        Return value
    End Function
    Public Shared Function newid() As String
        Dim thisNewID As String = String.Empty
        Dim String62 As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
        Dim Seconds As Integer
        Dim days As Integer
        System.Threading.Thread.Sleep(1)
        Seconds = CInt(Date.Now.TimeOfDay.TotalMilliseconds)
        Dim tmdays As TimeSpan = Date.Now.Subtract(#9/14/1752#)
        days = CInt(tmdays.TotalDays)
        While Seconds <> 0
            thisNewID = String62.Substring(Seconds Mod 62, 1) + thisNewID
            Seconds = CInt(Seconds / 62)
        End While
        While days <> 0
            thisNewID = String62.Substring(days Mod 62, 1) + thisNewID
            days = CInt(days / 62)
        End While
        thisNewID = thisNewID.PadLeft(10, CChar("0"))

        Return thisNewID
    End Function
    Public Shared Function GenerateHash(ByVal SourceText As String) As String
        Dim Ue As New UnicodeEncoding()
        Dim ByteSourceText() As Byte = Ue.GetBytes(SourceText)
        Dim Md5 As New MD5CryptoServiceProvider()
        Dim ByteHash() As Byte = Md5.ComputeHash(ByteSourceText)
        Return Convert.ToBase64String(ByteHash)
    End Function
    Public Shared Function WriteToXml(Of t)(ByVal filename As String, ByVal rec As t) As String
        Dim ErrorMessage As String = String.Empty
        If Not String.IsNullOrEmpty(filename) Then
            If Not IsNothing(rec) AndAlso Not String.IsNullOrEmpty(filename) Then
                Dim objStreamWriter As StreamWriter = Nothing
                Try
                    objStreamWriter = New StreamWriter(filename)
                    Dim x As New XmlSerializer(rec.GetType)
                    x.Serialize(objStreamWriter, rec)
                Catch ex As Exception
                    ErrorMessage = ex.Message
                End Try
                If Not IsNothing(objStreamWriter) Then
                    objStreamWriter.Close()
                End If
            End If
        Else
            ErrorMessage = "Empty file name."
        End If
        Return ErrorMessage
    End Function
    Public Shared Function ReadFromXML(Of t)(ByVal filename As String, ByRef rec As t) As String
        Dim ErrorMessage As String = String.Empty
        If Not String.IsNullOrEmpty(filename) Then
            Dim io As New IO.FileInfo(filename)
            If io.Exists Then
                Dim objStreamReader As New StreamReader(filename)
                Try
                    Dim x As New XmlSerializer(rec.GetType)
                    rec = CType(x.Deserialize(objStreamReader), t)
                Catch ex As Exception
                    ErrorMessage = ex.Message
                Finally
                    If Not IsNothing(objStreamReader) Then
                        objStreamReader.Close()
                    End If
                End Try
            End If
        End If
        Return ErrorMessage
    End Function
    Public Shared Sub InitGrid(ByRef dg As DataGridView)
        dg.Columns.Clear()
        Dim altcolor As Color = Color.FromArgb(215, 215, 255)
        Dim cellFont As Font = New Font("Arial", 8)
        Dim headerFont As Font = New Font("Arial", 8)
        Dim headerCellFont As New Font("Arial", 8, FontStyle.Underline)
        dg.AutoGenerateColumns = False
        dg.AllowUserToAddRows = False
        dg.AllowUserToDeleteRows = False
        dg.ReadOnly = True
        dg.AlternatingRowsDefaultCellStyle.BackColor = altcolor
        dg.ColumnHeadersDefaultCellStyle.Font = headerFont
        dg.RowsDefaultCellStyle.Font = cellFont
        dg.RowHeadersWidth = 17
        dg.EnableHeadersVisualStyles = False
        dg.RowTemplate.Height = 22
        dg.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing
        dg.ColumnHeadersHeight = 22
    End Sub
End Class
